import os
import yaml
import logging
from datetime import timedelta
from typing import Dict, Any, List

class ConfigManager:
    """配置管理器"""
    
    def __init__(self, config_path: str = None):
        if config_path is None:
            # 默认从项目根目录读取配置文件
            config_path = os.path.join(os.path.dirname(__file__), '..', 'config.yaml')
        
        self.config_path = config_path
        self._config = self._load_config()
        self._setup_logging()
        self._ensure_directories()
    
    def _load_config(self) -> Dict[str, Any]:
        """加载配置文件"""
        try:
            with open(self.config_path, 'r', encoding='utf-8') as f:
                config = yaml.safe_load(f)
            return config
        except FileNotFoundError:
            raise FileNotFoundError(f"配置文件未找到: {self.config_path}")
        except yaml.YAMLError as e:
            raise ValueError(f"配置文件格式错误: {e}")
    
    def _setup_logging(self):
        """设置日志配置"""
        log_config = self.get('logging', {})
        
        # 确保日志目录存在
        log_file = log_config.get('file', 'logs/app.log')
        log_dir = os.path.dirname(log_file)
        if log_dir:
            os.makedirs(log_dir, exist_ok=True)
        
        # 配置日志
        logging.basicConfig(
            level=getattr(logging, log_config.get('level', 'INFO')),
            format=log_config.get('format', '%(asctime)s - %(name)s - %(levelname)s - %(message)s'),
            handlers=[
                logging.FileHandler(log_file, encoding='utf-8'),
                logging.StreamHandler()
            ]
        )
    
    def _ensure_directories(self):
        """确保必要的目录存在"""
        upload_folder = self.get_upload_folder()
        temp_folder = self.get_temp_folder()
        
        os.makedirs(upload_folder, exist_ok=True)
        os.makedirs(temp_folder, exist_ok=True)
    
    def get(self, key: str, default: Any = None) -> Any:
        """获取配置值，支持点号分隔的嵌套键"""
        keys = key.split('.')
        value = self._config
        
        for k in keys:
            if isinstance(value, dict) and k in value:
                value = value[k]
            else:
                return default
        
        return value
    
    # 服务器配置
    def get_server_host(self) -> str:
        return self.get('server.host')
    
    def get_server_port(self) -> int:
        return self.get('server.port')
    
    def get_server_debug(self) -> bool:
        return self.get('server.debug')
    
    def get_server_use_reloader(self) -> bool:
        return self.get('server.use_reloader')
    
    # API配置
    def get_api_base_url(self) -> str:
        # 动态生成base_url，使用server配置
        host = self.get_server_host()
        port = self.get_server_port()
        # 如果host是0.0.0.0，在URL中使用localhost代替
        url_host = 'localhost' if host == '0.0.0.0' else host
        return f"http://{url_host}:{port}/api"
    
    def get_cors_origins(self) -> List[str]:
        origins = self.get('api.cors_origins')
        # 动态添加前端配置的URL
        frontend_host = self.get_frontend_host()
        frontend_port = self.get_frontend_port()
        frontend_url = f"http://{frontend_host}:{frontend_port}"
        if frontend_url not in origins:
            origins.append(frontend_url)
        return origins
    
    # 文件配置
    def get_max_file_size(self) -> int:
        return self.get('files.max_file_size')
    
    def get_upload_folder(self) -> str:
        folder = self.get('files.upload_folder')
        if not os.path.isabs(folder):
            folder = os.path.join(os.path.dirname(__file__), '..', folder)
        return os.path.abspath(folder)
    
    def get_temp_folder(self) -> str:
        folder = self.get('files.temp_folder')
        if not os.path.isabs(folder):
            folder = os.path.join(os.path.dirname(__file__), '..', folder)
        return os.path.abspath(folder)
    
    def get_allowed_extensions(self) -> set:
        extensions = self.get('files.allowed_extensions')
        return set(extensions)
    
    def get_cleanup_interval_hours(self) -> int:
        return self.get('files.cleanup_interval_hours')
    
    def get_temp_file_lifetime(self) -> timedelta:
        hours = self.get('files.temp_file_lifetime_hours')
        return timedelta(hours=hours)
    
    # 转换配置
    def get_conversion_timeout(self) -> int:
        return self.get('conversion.timeout_seconds')
    
    def get_supported_formats(self) -> List[Dict[str, str]]:
        return self.get('conversion.supported_formats')
    
    def get_conversion_matrix(self) -> Dict[str, List[str]]:
        return self.get('conversion.conversion_matrix')
    
    # 安全配置
    def get_secret_key(self) -> str:
        # 优先从环境变量获取
        secret_key = os.environ.get('SECRET_KEY')
        if secret_key:
            return secret_key
        return self.get('security.secret_key')
    
    # 环境配置
    def get_environment(self) -> str:
        # 优先从环境变量获取
        env = os.environ.get('FLASK_ENV') or os.environ.get('ENVIRONMENT')
        if env:
            return env
        return self.get('environment.name')
    
    def is_development(self) -> bool:
        return self.get_environment() == 'development'
    
    def is_production(self) -> bool:
        return self.get_environment() == 'production'
    
    def is_testing(self) -> bool:
        return self.get_environment() == 'testing'
    
    def reload_config(self):
        """重新加载配置文件"""
        self._config = self._load_config()
        self._setup_logging()
        self._ensure_directories()
    
    # 前端配置
    def get_frontend_host(self) -> str:
        return self.get('frontend.host')
    
    def get_frontend_port(self) -> int:
        return self.get('frontend.port')

# 全局配置实例
config_manager = ConfigManager() 